package com.aca.market.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 *
 * @author ksqqxq
 * trigger setter or getter method by java refection
 *
 **/

public class ReflectionUtils {

    private static ReflectionUtils instacnce = null;

    private ReflectionUtils() {

    }

    public static ReflectionUtils getInstance() {
        if (instacnce == null) {
            instacnce = new ReflectionUtils();
        }
        return instacnce;
    }

    /**
     * @param : obj. the operating obj
     * @param : attribute. the attribute you want to set
     * */
    @SuppressWarnings("unchecked")
    private String invokeGetterMethod(Object obj, String attribute)throws Exception {

        Class clazz = obj.getClass();
        System.out.println(getMethodName(true,attribute));
        Method method = clazz.getMethod(getMethodName(true,attribute));

        return method.invoke(obj).toString();
    }

    /**
     * @param : obj. the operating obj
     * @param : attribute. the attribute you want to set
     * @param : value. the value you want to set
     * */
    @SuppressWarnings("unchecked")
    public void invokeSetterMethod(Object obj , String attribute, Object value) throws Exception{
        Class clazz = obj.getClass();
        Field field = clazz.getDeclaredField(attribute);
        Class paramType = field.getType();
        Method method = clazz.getMethod(getMethodName(false,attribute), paramType);
        method.invoke(obj, value);

    }

    /**
     * @param : flag. which method you will get
     * @param : attribute. which attribute you will get
     * */
    private String getMethodName(boolean flag ,String attribute) {
        String firstElemntOfAttribute = attribute.substring(0, 1).toUpperCase();
        String restElementOfAttrute = attribute.substring(1);
        return (flag ? "get"  : "set")  +  firstElemntOfAttribute + restElementOfAttrute;
    }

}
